import { ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import type { CreditFeedback } from '@/interface/CreditFeedbackData'
import { useUserStore } from "@/stores/userStore";


export default function () {
      const reportList = ref<CreditFeedback[]>([]);
      const loading = ref(false);
      const dialogVisible = ref(false);
      const currentReport = ref<CreditFeedback | null>(null);
      const userStore = useUserStore();

      // 历史记录
      const globalHistoryDialogVisible = ref(false);
      const globalHistoryList = ref<CreditFeedback[]>([]);
      const globalHistoryLoading = ref(false);



      const auditForm = ref({
            auditOpinion: "",
            scoreChange: 0,
      });

      // 图片查看弹框控制
      const imageDialogVisible = ref(false);
      // 解析当前举报的材料图片链接，逗号分隔转数组
      const evidenceImages = ref<string[]>([]);

      // 拉取举报列表
      async function REQ_fetchReports() {
            loading.value = true;
            try {
                  const res = await axios.get("/api/institute/reportList");
                  reportList.value = res.data.data;
            } catch (e) {
                  ElMessage.error("加载举报信息失败");
            } finally {
                  loading.value = false;
            }
      }

      // 审核提交
      async function REQ_submitAudit(payload: {
            id: number;
            auditOpinion: string;
            scoreChange: number;
            status: string;
            auditorId: number|null;
            targetUserId: number;
            description: string;
      }) {
            try {
                  await axios.post("/api/institute/reportSubmit", payload);
                  ElMessage.success("审核成功");
                  dialogVisible.value = false;
                  await REQ_fetchReports();
            } catch (e) {
                  ElMessage.error("审核失败");
            }
      }

      // 打开审核弹窗
      function openDialog(row: CreditFeedback) {
            currentReport.value = { ...row };
            auditForm.value = {
                  auditOpinion: "",
                  scoreChange: 0,
            };

            evidenceImages.value = row.evidenceUrl
                  ? row.evidenceUrl
                        .split(",")
                        .map((url) => url.trim())
                        .filter((url) => url)
                  : [];

            dialogVisible.value = true;
      }

      // 提交审核按钮事件
      async function submitAudit(status: "通过" | "驳回") {
            if (!currentReport.value) return;

            await REQ_submitAudit({
                  id: currentReport.value.id,
                  auditOpinion: auditForm.value.auditOpinion,
                  scoreChange: auditForm.value.scoreChange,
                  status,
                  description: currentReport.value.description,
                  auditorId: userStore.useridentityfer, // 这里可以改成动态管理员ID
                  targetUserId: currentReport.value.targetUserId, // ✅ 传入
            });
      }

      // 打开图片查看弹框
      function openImageDialog() {
            if (evidenceImages.value.length === 0) {
                  ElMessage.warning("没有材料图片");
                  return;
            }
            imageDialogVisible.value = true;
      }

      // 关闭图片弹框
      function handleImageDialogClose() {
            imageDialogVisible.value = false;
      }

      async function openGlobalHistory() {
            globalHistoryDialogVisible.value = true;
            globalHistoryLoading.value = true;
            try {
                  const res = await axios.get("/api/institute/reportHistories");
                  globalHistoryList.value = res.data.data;
            } catch (e) {
                  ElMessage.error("加载全部审核记录失败");
            } finally {
                  globalHistoryLoading.value = false;
            }
      }


      onMounted(() => {
            REQ_fetchReports();
      });

      return {
            reportList,
            loading,
            dialogVisible,
            currentReport,
            auditForm,
            openDialog,
            submitAudit,
            imageDialogVisible,
            openImageDialog,
            handleImageDialogClose,
            evidenceImages,
            globalHistoryDialogVisible,
            globalHistoryList,
            globalHistoryLoading,
            openGlobalHistory,
      };
}
